<?php

namespace App\Services\ApplyGoldProductOrder;

use Carbon\Carbon;
use App\Models\User;
use App\Models\Order;
use App\Models\Address;
use App\Models\GoldRecord;
use App\Models\GoldProduct;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
use App\Services\MakeProductOrder\MakeProductOrder;

class ApplyGoldProductOrder
{
	protected User $user;

	protected ?Address $address = null;

	protected ?GoldRecord $goldRecord = null;

	protected ?GoldProduct $goldProduct = null;

	public function __construct(User $user, string $pendingCacheId, Address $address)
	{
		$this->user = $user;

		$recordId = (int)Redis::hGet($pendingCacheId, 'gold_record_id');
		$record = $recordId > 0 ? GoldRecord::find($recordId) : null;

		if ($record) {
			$this->goldRecord = $record;
			$this->goldProduct = $record->goldProduct;
			$this->address = $address;
		}
	}

	protected function items(): array
	{
		return [[
			'sku_id' => $this->goldRecord->product_sku_id,
			'amount' => 1
		]];
	}

	protected function updateGoldRecord()
	{
		$this->goldRecord->update(['to_take_applied_at' => Carbon::now()]);
        $this->goldProduct->update(['disabled_at' => Carbon::now()]);
	}

	protected function createRecordOrder()
	{
		return DB::transaction(function () {

            $order = app(MakeProductOrder::class, [
				'user' => $this->user,
				'address' => $this->address,
				'items' => $this->items(),
				'record' => $this->goldRecord,
			])->make();

			$this->updateGoldRecord();

            account_coins($this->user)->minusOrderPaid($this->goldRecord->pay_cash_price);

			return $order;
		});
	}

	public function apply()
	{
		if (Order::isAddressSupported($this->address)) {
			$this->createRecordOrder();
			$this->user->markRecordCacheAsTake($this->goldRecord);
		}
	}
}
